package com.tjtt.tdm.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tjtt.tdm.exception.DaoException;
import com.tjtt.tdm.exception.ServiceException;
import com.tjtt.tdm.system.bean.Menu;
import com.tjtt.tdm.system.bean.Opratingbutton;
import com.tjtt.tdm.system.bean.Rolemenu;
import com.tjtt.tdm.system.dao.MenuDao;
import com.tjtt.tdm.system.dao.PipeDao;
import com.tjtt.tdm.system.dao.RoleMenuDao;
import com.tjtt.tdm.system.service.MenuService;
import com.tjtt.tdm.system.service.PipeService;

public class PipeServiceImpl implements PipeService {
	private static final Log log = LogFactory.getLog(PipeServiceImpl.class);
	private PipeDao menuDao;
	private RoleMenuDao roleMenuDao;
	public List<Menu> findMenuByParentId(Long parentId) throws ServiceException {
		try {
			return menuDao.findMenuByParentId(parentId);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}

	public String saveMenu(Menu menu) throws ServiceException {
		String id = "";
		try {
			menu.setChildrennum(0L);
			long sequence = menuDao.getMenuSequenceByParentId(menu.getParentid());
			menu.setSequence(sequence+1);
			menuDao.save(menu);
			id = String.valueOf(menu.getMenuid());
			if(menu.getParentid().intValue() != 1){
				Menu menuTemp = menuDao.get(menu.getParentid());
				menuTemp.setChildrennum(menuTemp.getChildrennum()+1);
				menuDao.update(menuTemp);
			}
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
		return id;
	}

	public void delMenu(Long menuId) throws ServiceException {
		try {
			Menu delMenu = menuDao.get(menuId);
			Long parentid = delMenu.getParentid();
			long seq = delMenu.getSequence();
			if(parentid.intValue() != 1){
				Menu parentMenu = menuDao.get(parentid);
				parentMenu.setChildrennum(parentMenu.getChildrennum() - 1);
				menuDao.update(parentMenu);
			}
			roleMenuDao.removeByParams(Rolemenu.class,"menuid", new Long[]{menuId});
			menuDao.updateUpMenusPosition(parentid, seq);
			menuDao.remove(delMenu);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}
	
	public void updateMenu(Menu menu) throws ServiceException {
		try {
			Menu tempMenu = menuDao.get(menu.getMenuid());
			tempMenu.setMenuname(menu.getMenuname());
			tempMenu.setMenudesc(menu.getMenudesc());
			tempMenu.setUrl(menu.getUrl());
			menuDao.update(tempMenu);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}
	
	public Menu getMenuById(Long menuId) throws ServiceException {
		try {
			return menuDao.get(menuId);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}

	public List<Menu> findMenuByRoleId(Long parentId,String roleId) throws ServiceException{
		try {
			String[] str = roleId.split(",");
			Long[] roleids = new Long[str.length];
			for(int i=0;i<str.length;i++){
				roleids[i] = Long.valueOf(str[i]);
			}
			List<Menu> menuList = menuDao.findMenuByRoleId(parentId, roleId);
			return menuList;
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}
	public List<Menu> getAllMenu() throws ServiceException{
		try {
			return menuDao.getAll();
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}
	public void setRoleMenuDao(RoleMenuDao roleMenuDao) {
		this.roleMenuDao = roleMenuDao;
	}

	public void setMenuDao(PipeDao menuDao) {
		this.menuDao = menuDao;
	}

	public List<Menu> findByProperty(String menuname) throws ServiceException {
		try {
			return menuDao.findByProperty("menuname",menuname);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}
 
	
	public String getRoleModulebutton(String roleid, String moduleid) throws ServiceException {
		 try {
			 String sql = "SELECT tt.BUTTONKEY"+
				 " FROM SYS_OPRATINGBUTTON TT"+
				 " WHERE TT.OPRATINGBUTTONID"+
				 " NOT IN (SELECT T.OPRATINGBUTTONID"+
				 " FROM SYS_ROLEMENUOPERATION T"+
				 " WHERE T.ROLEID IN (" + roleid + ")"+
				 " AND T.MENUEID = "+ moduleid +")"+
				 " AND tt.MENUID="+ moduleid;
//			 String sql = "SELECT b.BUTTONKEY"+
//			    " FROM ROLEMENUOPERATION T"+
//				" LEFT JOIN OPRATINGBUTTON B"+
//				" ON B.OPRATINGBUTTONID = T.OPRATINGBUTTONID"+
//				" WHERE T.ROLEID in (" + roleid + ")" + 
//				" AND T.MENUEID = " + moduleid;
			 List list =menuDao.findBySQL(sql);
			 String buttonids = "";
			 if(list!= null && list.size()>0){
				for(int i=0;i<list.size();i++){
					HashMap button = (HashMap)list.get(i);
					String buttonid = String.valueOf(button.get("BUTTONKEY"));
					buttonids += buttonid + ",";
				}
				return  buttonids.substring(0,buttonids.length()-1);
			 }
		 } catch (DaoException e) {
			// TODO Auto-generated catch block
			throw new ServiceException(e.getMessage(),e);
		 } 
		return null;
	}

	public String queryMenuTree() throws ServiceException{
		try {
			String menuTree = getChild("0");
			return menuTree;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public String queryMenuTreeClose() throws ServiceException{
		try {
			String menuTree = getChildClose("0");
			return menuTree;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
    private String getJson(String id, String name,String colName,String sql) throws DaoException
    {
    	String strJson="";
    	//strJson="{\"id\":"+id+",\"text\":\""+name+"\",\"state\":\"open\",";
    	strJson+="{\"id\":"+id+",\"text\":\""+name+"\",\"state\":\"open\",";
    	strJson+="\"children\":[";	
    	List list=menuDao.findBySQL(sql);
    	if(list.size()>0){
    		for (int i = 0; i < list.size()-1; i++) {
    			Map<String,String> map=(Map<String, String>) list.get(i);				
    			//id=String.valueOf(i+2);
    			id=map.get("ID");
    			String pipeNo=map.get(colName);	
    			strJson+="{\"id\":"+id+",\"text\":\""+pipeNo+"\",\"state\":\"open\"},";
    		}
    		Map<String,String> map=(Map<String, String>) list.get(list.size()-1);
    		//id=map.get("ID");
    		String pipeNo=map.get(colName);
    		//id=String.valueOf(list.size()-1+2);
    		id=map.get("ID");
    		strJson+="{\"id\":"+id+",\"text\":\""+pipeNo+"\",\"state\":\"open\"}]}";
    	}
    	
    	return strJson;	
    }
	/*private String getChild(String parentid) throws DaoException{
		//定义变量
		String strResult="";
		String temp = "";
		//根节点
		String id="0";
		String name="北京管网";	
		temp="{\"id\":"+id+",\"text\":\""+name+"\",\"state\":\"open\",";
		strResult+=temp;
		strResult+="\"children\":[";	
		//管线
		id="1";
		name="管线";
		String sql="select ID,PIPELINENO from PTEM_PIPELINE";
		String colName="PIPELINENO";
		temp=getJson(id,name,colName,sql);
		strResult+=temp;
		//站箱
		strResult+=",";
		id="2";
		name="站箱";
		sql="select ID,PIPENO from PTEM_STATION";
		colName="PIPENO";
		temp=getJson(id,name,colName,sql);
		strResult+=temp;
		//
		strResult+="]}";
		return strResult;
	}
	*/
    private String getJsonPipeSection(String pipeLineNo){
    	String strJson="";
    	
    	return strJson;
    }
	private String getChild(String parentid) throws DaoException{
			//定义变量
			String strResult="";
			String temp = "";
			//根节点
			String id="0";
			String name="北京管网";	
			temp="{\"id\":"+id+",\"text\":\""+name+"\",\"state\":\"open\",\"children\":[";
			strResult+=temp;
			String strJson="";
			String sql="";
			List list;
			String pipeLineColName;
			//管线
			id="1";
			name="管线";
	    	strJson+="{\"id\":"+id+",\"text\":\""+name+"\",\"state\":\"open\",\"children\":[";
	    	sql="select ID,PIPELINENO from PTEM_PIPELINE";
	    	pipeLineColName="PIPELINENO";
	    	String pipeSectionColName="PIPESECTIONNO";
			Map<String,String> map;
			String pipeLineNo;
			String pipeSectionNo;
			//查询管线编号
	    	list=menuDao.findBySQL(sql);
	    	if(list.size()>0){
	    		for (int i = 0; i < list.size(); i++) {
	    			map=(Map<String, String>) list.get(i);				
	    			id=map.get("ID");
	    			pipeLineNo=map.get(pipeLineColName);	
	    			//管线
	    			strJson+="{\"id\":"+id+",\"text\":\""+pipeLineNo+"\",\"state\":\"open\",\"children\":[";
	    			//管段
	    			id="2";
	    			name="管段";
	    	    	strJson+="{\"id\":"+id+",\"text\":\""+name+"\",\"state\":\"open\"";
	    	    	sql="select ID,PIPESECTIONNO from PTEM_PIPESECTION where PIPELINENO='";
	    	    	sql+=pipeLineNo;
	    	    	sql+="'";
	    	    	List pipeSectionlist=menuDao.findBySQL(sql);
	    	    	int num=pipeSectionlist.size();
	    	    	if(num<=0)
	    	    	{
	    	    		strJson+="}]},";
	    	    		continue;
	    	    	}
	    	    	strJson+=",\"children\":[";	
	    	    	for(int j=0;j<num;j++)
	    	    	{
	    	    		map=(Map<String, String>) pipeSectionlist.get(j);				
	        			id=map.get("ID");
	        			pipeSectionNo=map.get(pipeSectionColName);	
	        			strJson+="{\"id\":"+id+",\"text\":\""+pipeSectionNo+"\",\"state\":\"open\"},";
	    	    	}
	    	    	strJson = strJson.substring(0,strJson.length()-1);
	        		strJson+="]}"; 
	        		//--管段
	        		//--一条管线
	        		strJson+="]},";
	    		}
	    		strJson = strJson.substring(0,strJson.length()-1);
	    	}
			strResult+=strJson;
			
			//--所有管线
			strResult+="]},";
			//站箱
			id="2";
			name="站箱";
			sql="select ID,STATIONNAME from PTEM_STATION";
			String stationColName="STATIONNAME";
			temp=getJson(id,name,stationColName,sql);
			strResult+=temp;
			//
			strResult+="]}";
			return strResult;
		}
		

	/*private String getChild(String parentid) throws DaoException{
		
		
		//定义变量
		String strResult="";
		String temp = "";
		//根节点
		String id="0";
		String name="北京管网";	
		temp="{\"id\":"+id+",\"text\":\""+name+"\",\"state\":\"open\",\"children\":[";
		strResult+=temp;
		String strJson="";
		String sql="";
		List list;
		String pipeLineColName;
		//管线
		id="1";
		name="管线";
    	strJson+="{\"id\":"+id+",\"text\":\""+name+"\",\"state\":\"open\",\"children\":[";
    	sql="select ID,PIPELINENO from PTEM_PIPELINE";
    	pipeLineColName="PIPELINENO";
    	String pipeSectionColName="PIPESECTIONNO";
		Map<String,String> map;
		String pipeLineNo;
		String pipeSectionNo;
		//查询管线编号
    	list=menuDao.findBySQL(sql);
    	if(list.size()>0){
    		for (int i = 0; i < list.size(); i++) {
    			map=(Map<String, String>) list.get(i);				
    			id=map.get("ID");
    			pipeLineNo=map.get(pipeLineColName);	
    			//管线
    			strJson+="{\"id\":"+id+",\"text\":\""+pipeLineNo+"\",\"state\":\"open\",\"children\":[";
    			//管段
    			id="2";
    			name="管段";
    	    	strJson+="{\"id\":"+id+",\"text\":\""+name+"\",\"state\":\"open\"";
    	    	sql="select ID,PIPESECTIONNO from PTEM_PIPESECTION where PIPELINENO='";
    	    	sql+=pipeLineNo;
    	    	sql+="'";
    	    	List pipeSectionlist=menuDao.findBySQL(sql);
    	    	int num=pipeSectionlist.size();
    	    	if(num<=0)
    	    	{
    	    		strJson+="}]},";
    	    		continue;
    	    	}
    	    	strJson+=",\"children\":[";	
    	    	for(int j=0;j<num;j++)
    	    	{
    	    		map=(Map<String, String>) pipeSectionlist.get(j);				
        			id=map.get("ID");
        			pipeSectionNo=map.get(pipeSectionColName);	
        			strJson+="{\"id\":"+id+",\"text\":\""+pipeSectionNo+"\",\"state\":\"open\"},";
    	    	}
    	    	strJson = strJson.substring(0,strJson.length()-1);
        		strJson+="]}"; 
        		//--管段
        		//--一条管线
        		strJson+="]},";
    		}
    		strJson = strJson.substring(0,strJson.length()-1);
    	}
		strResult+=strJson;
		
		//--所有管线
		strResult+="]},";
		//站箱
		id="2";
		name="站箱";
		sql="select ID,STATIONNAME from PTEM_STATION";
		String stationColName="STATIONNAME";
		temp=getJson(id,name,stationColName,sql);
		strResult+=temp;
		//
		strResult+="]}";
		return strResult;
	}
	*/private String getChildClose(String parentid) throws DaoException{
		String hql = "from Menu m where m.parentid="+Long.parseLong(parentid) +" order by sequence"; 
		List<Menu> list = menuDao.executeHql(hql);
		String temp = "";
		String isopen = "open";
		if(list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				Menu objs = list.get(i);
				String sql2 = "from Menu m where m.parentid=" +objs.getMenuid();
				int count = menuDao.executeHql(sql2).size();
				if(count>0){//如果是多个
					temp += "{\"id\":"+objs.getMenuid()+",\"text\":\""+objs.getMenuname()+"\",\"state\":\""+isopen+"\",\"children\":["+getChildClose(String.valueOf(objs.getMenuid()))+"]},";
				}else{
					temp += "{\"id\":"+objs.getMenuid()+",\"text\":\""+objs.getMenuname()+"\",\"attributes\":{\"url\":\""+objs.getUrl()+"\"}},";
				}
				if (isopen.equals("open")){
					isopen = "closed";
				}
			}
		}
		if(temp.length()>0){
			temp = temp.substring(0,temp.length()-1);
		}
		return temp;
	}
	/**
	 * 查询菜单对应按钮
	 * author:lishu	 2015-3-4
	 */
	public String queryMenuButton(String menuId) throws ServiceException{
		try {
			String hql = "from Opratingbutton o where o.menuid="+Long.parseLong(menuId); 
			List<Opratingbutton> list = menuDao.executeHql(hql);
			String temp = "";
			for (int i = 0; i < list.size(); i++) {
				Opratingbutton button = list.get(i);
				temp += "{\"buttonId\":"+button.getOpratingbuttonid()+",\"buttonKey\":\""+button.getButtonkey()+"\",\"buttonName\":\""+button.getButtonname()+"\",\"requestUrl\":\""+button.getRequesturl()+"\"},";
			}
			if(temp.length()>0){
				temp = temp.substring(0,temp.length()-1);
			}
			return "{\"total\":"+list.size()+",\"rows\":["+temp+"]}";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
	public void saveMenuButton(Opratingbutton button) throws ServiceException {
		try {
			menuDao.save(button);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}

	
	public void delMenuButton(Long buttonId) throws ServiceException {
		try {
			List<Opratingbutton> list = menuDao.executeHql("from  Opratingbutton o where o.opratingbuttonid="+buttonId);
			menuDao.remove(list.get(0));
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}

	
	public void updateMenuButton(Opratingbutton button) throws ServiceException {
		try {
			menuDao.update(button);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}

	
	public Opratingbutton getMenuButtonById(Long buttonId)
			throws ServiceException {
		try {
			List<Opratingbutton> list = menuDao.executeHql("from  Opratingbutton o where o.opratingbuttonid="+buttonId);
			return list.get(0);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}

	
	public void executeSQL(String hql) throws ServiceException {
		try {
			menuDao.executeSQL(hql);
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}
	
	public List<Menu> executeHql(String hql) throws ServiceException {
		try {
			return menuDao.executeHql(hql);
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(),e);
		}
	}
}
